//
//  UtilForFileCache.m
//  RNRecorder
//
//  Created by GJS on 2018/8/17.
//  Copyright © 2018年 GJS. All rights reserved.
//

#import "UtilForFileCache.h"

@interface UtilForFileCache()
@end

@implementation UtilForFileCache

+ (instancetype)instance {
    static UtilForFileCache *m;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!m) {
            m = [[UtilForFileCache alloc] init];
        }
    });
    return m;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        self.fileManager = [[NSFileManager alloc] init];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        _cachePath = [paths[0] stringByAppendingPathComponent:@"file_cache"];
        if (![self.fileManager fileExistsAtPath:self.cachePath]) {
            [self.fileManager createDirectoryAtPath:self.cachePath withIntermediateDirectories:YES attributes:nil error:NULL];
        }
    }
    return self;
}

- (BOOL)storeFile:(NSData *)data toPath:(NSString *)path {
    if (!path) {
        return NO;
    }
    NSString *savePath = path;
    NSString *filename = [path lastPathComponent];
    NSArray *pathComponents = [path pathComponents];
    if (pathComponents.count > 1) {
        savePath = path;
    } else {
        savePath = [self.cachePath stringByAppendingPathComponent:filename];
    }
    return [self.fileManager createFileAtPath:savePath contents:data attributes:nil];
}

- (BOOL)removeFile:(NSString *)path {
    if (!path) {
        return NO;
    }
    NSString *removePath = path;
    NSString *filename = [path lastPathComponent];
    NSArray *pathComponents = [path pathComponents];
    if (pathComponents.count > 1) {
        removePath = path;
    } else {
        removePath = [self.cachePath stringByAppendingPathComponent:filename];
    }
    return [self.fileManager removeItemAtPath:removePath error:nil];
}

@end

